package tq.com.tqstudent.ui.activity.mine;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.cropimage.tq.ImagePicker;
import com.cropimage.tq.cropper.CropImage;
import com.cropimage.tq.cropper.CropImageView;
import com.lib.common.base.BaseActivity;
import com.lib.common.utils.FileUtil;
import com.lib.common.utils.ImgUtils;
import com.lib.common.utils.LogUtil;
import com.lib.common.utils.PermissionConstant;
import com.lzy.okgo.OkGo;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import tq.com.tqstudent.App;
import tq.com.tqstudent.R;
import tq.com.tqstudent.bean.SimpleBaseBean;
import tq.com.tqstudent.bean.UserInfo;
import tq.com.tqstudent.net.ok.SimpleDialogCallback;
import tq.com.tqstudent.utils.MatisseImageEngine;
import tq.com.tqstudent.utils.VarietyUtil;
import tq.com.tqstudent.views.PhotoTipsDialog;

/**
 * @Author rames
 * @date 2019/3/21 17:01
 */
public class HeadImgActivity extends BaseActivity {
    @BindView(R.id.head_iv)
    ImageView headIV;
    private String imgName = "default.jpg";
    private ImagePicker imagePicker;
//    private Bitmap headBitmap;

    public static void show(Activity activity){
        Intent intent = new Intent(activity, HeadImgActivity.class);
        Bundle bundle = new Bundle();
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    @Override
    public int initLayout() {
        return R.layout.activity_head_img;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        initImagePicker();
        setStatusBarColor(R.color.black);
//        findViewById(R.id.title_text).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                headIV.setImageBitmap(ImgUtils.rotateBitmap(headBitmap, 90));
//            }
//        });
//        headBitmap = BitmapFactory.decodeFile("/storage/emulated/0/Pictures/JPEG_20190509_182708.jpg");
//        headIV.setImageBitmap(headBitmap);
        Glide.with(this).load(VarietyUtil.getHeadImgUri(UserInfo.getHeadImg())).apply(VarietyUtil.getGlideHeadOptions()).into(headIV);
    }

    int i = 0;
    @OnClick(R.id.right_layout)
    public void onClick(View v){
        PhotoTipsDialog dialog = new PhotoTipsDialog(this);
        dialog.setCallback(chooseCallback);
        dialog.show();
    }

    private PhotoTipsDialog.ChooseCallback chooseCallback = new PhotoTipsDialog.ChooseCallback() {
        @Override
        public void choose(int index) {
            // 相机
            if(index == 1){
                getPermission(true);

                // 相册
            } else if (index == 2){
                getPermission(false);

                // 保存
            } else {
//                String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + Constants.APP_FOLDER;
//                showToast(ImgUtils.saveImageToGallery(HeadImgActivity.this, storePath, imgName, bitmap) ? "保存成功" : "保存失败");
            }
        }
    };

    @Override
    public void initData() {

    }

    private void getPermission(boolean isCamera){
        AndPermission.with(this)
                .runtime()
                .permission(PermissionConstant.PERMISSIONS_OF_IMAGE)
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> permissions) {
                        headPicker(isCamera);
                    }
                })
                .onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> permissions) {
                        showToast("用户已禁止访问图片权限");
                    }
                })
                .start();
    }

    private void headPicker(boolean isCamera){
        Matisse.from(this)
                .choose(MimeType.of(MimeType.PNG, MimeType.JPEG))
                .countable(true)
                .maxSelectable(1)
                .capture(false)
                .isCamera(isCamera)
                .isSimpleChoose(true)
                .captureStrategy(new CaptureStrategy(true, "tq.com.tqstudent.fileProvider"))
//                .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.dp_120))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new MatisseImageEngine())
                .forResult(REQUEST_CODE_CHOOSE);
    }

    private void initImagePicker(){
        imagePicker = new ImagePicker();
        // 设置标题
        imagePicker.setTitle("设置头像");
        // 设置是否裁剪图片
        imagePicker.setCropImage(true);
        imagePicker.setCallback(cropCallback);
    }

    private ImagePicker.Callback cropCallback = new ImagePicker.Callback(){
        // 选择图片回调
        @Override public void onPickImage(Uri imageUri) {

        }

        // 裁剪图片回调
        @Override public void onCropImage(Uri imageUri) {
            headIV.setImageURI(imageUri);
            uploadHeadTask(FileUtil.getFilePathByUri(HeadImgActivity.this, imageUri));
        }

        // 自定义裁剪配置
        @Override public void cropConfig(CropImage.ActivityBuilder builder) {
            builder
                    // 是否启动多点触摸
                    .setMultiTouchEnabled(false)
                    // 设置网格显示模式
                    .setGuidelines(CropImageView.Guidelines.OFF)
                    // 圆形/矩形
                    .setCropShape(CropImageView.CropShape.OVAL)
                    // 调整裁剪后的图片最终大小
                    .setRequestedSize(960, 540)
                    // 宽高比
                    .setAspectRatio(10, 10);
        }

        // 用户拒绝授权回调
        @Override public void onPermissionDenied(int requestCode, String[] permissions, int[] grantResults) {
        }
    };

    private List<String> images = new ArrayList<>();
    private final int REQUEST_CODE_CHOOSE = 135;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            images = Matisse.obtainPathResult(data);
//            headBitmap = BitmapFactory.decodeFile(images.get(0));
            if(images.size() > 0) {
                headIV.setImageURI(Uri.fromFile(new File(images.get(0))));
            }
            imagePicker.setCallback(cropCallback);
            imagePicker.handlePickImage(this, images.get(0));
        } else {
            Glide.with(this).load(VarietyUtil.getHeadImgUri(UserInfo.getHeadImg())).apply(VarietyUtil.getGlideHeadOptions()).into(headIV);
            imagePicker.onActivityResult(this, requestCode, resultCode, data);
        }
    }

    /** 上传头像 */
    private void uploadHeadTask(String path){
        OkGo.<SimpleBaseBean>post(App.getUploadUrl())
                .tag(this)
                .isMultipart(true)
                .params("file_type", "jpg")
                .params("file_tag", "head image")
                .params("file", new File(path))
                .execute(new SimpleDialogCallback(this) {
                    @Override
                    public void handleSuccess(SimpleBaseBean data) {
                        if(data.isSuccess()){
                            EventBus.getDefault().post(data);
                        }
                    }
                });
    }
}
